/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.lifecycle;

import com.techshop.controller.StaffLoginController;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author Hai-PC
 */
public class SecurityPhaseListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getSession(true);

        // check if view is protected
        UIViewRoot view = context.getViewRoot();
        if (view != null) {
            String viewId = view.getViewId();
            //Admin
            boolean authenticationRequired = viewId.contains("/admin/");
            boolean loggedIn = isLoggedIn();
            if (authenticationRequired && !loggedIn) {
                // send staff to login page if not logged in
                context.getApplication().getNavigationHandler().handleNavigation(context, null, "login");
            }
        }
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

    // Check Staff login
    private boolean isLoggedIn() {
        boolean loggedIn;
        FacesContext ctx = FacesContext.getCurrentInstance();
        StaffLoginController controller = (StaffLoginController) ctx.getApplication().evaluateExpressionGet(
                ctx, "#{staffLoginController}", Object.class);
        loggedIn = controller.isLoggedIn();
        return loggedIn;
    }
}
